import { computed, onMounted, ref } from "vue";

interface Product {
  id?: number;
  thumb?: string;
  name?: string;
  discount?: string;
  discount_old?: string;
  pinglun_num?: string;
  sales_num?: string;
  no?: string;
  uuid?: string;
  cover?: string;
  price?: string;
  product_id?: number;
  specification?: string;
  info?: string;
}
export default function useCar() {
  const carPopup = ref();
  const cacheProducts = uni.getStorageSync("products");

  const list = ref<Product[]>(cacheProducts ? JSON.parse(cacheProducts) : []);

  const showCount = computed(() => {
    return list.value.length > 99 ? "99+" : list.value.length;
  });
  const showCarPopup = () => {
    carPopup.value.open();
  };
  const pushProduct = (product: Product) => {
    const hasProduct = list.value.some(
      item => item.product_id === product.product_id
    );
    if (!hasProduct) {
      if (list.value.length > 5) {
        list.value = [...list.value.slice(1), product];
      } else {
        list.value.push(product);
      }
      uni.setStorageSync("products", JSON.stringify(list.value));
    }
  };
  return {
    carPopup,
    showCount,
    list,
    pushProduct,
    showCarPopup
  };
}
